/*
 * Copyright (c) 2021-2021 harkue
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package org.harkue.pkglock.integrity;

import org.apache.commons.io.IOUtils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 生成Integrity值
 *
 * @author harkue
 * @date 2021/12/18
 */
public class IntegrityGenerator {

    /**
     * 计算文件的Hash值，并采用Base64字符串返回
     *
     * @param file      NPM包文件
     * @param algorithm 算法
     * @return Hash值
     */
    public String genIntegrity(File file, String algorithm) throws Exception {
        PkgEncryptor encryptor = new PkgEncryptor();
        return encryptor.getFileHash(file, algorithm);
    }

    /**
     * 计算远程文件的Hash值，并采用Base64字符串返回
     *
     * @param url       NPM包远程链接
     * @param algorithm 算法
     * @return Hash值
     */
    public String genIntegrity(String url, String algorithm) {
        try {
            URL urlResource = new URL(url);
            BufferedInputStream inputStream = new BufferedInputStream(urlResource.openStream());

            PkgEncryptor encryptor = new PkgEncryptor();
            return algorithm + "-" + encryptor.getInputStreamHash(inputStream, algorithm);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 根据URL下载远程文件
     *
     * @param url 远程文件URL
     * @return 本地文件
     */
    public File downloadFile(String url) {
        File pkgFile = null;
        try {
            URL urlResource = new URL(url);
            BufferedInputStream inputStream = new BufferedInputStream(urlResource.openStream());

            String filename = retrieveFileNameFromUrl(url);
            pkgFile = new File(filename);

            FileOutputStream fos = new FileOutputStream(pkgFile);

            IOUtils.copy(inputStream, fos);

            fos.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return pkgFile;
    }

    /**
     * 通过URL计算文件名
     *
     * @param url 远程文件URL
     * @return 文件名
     * @throws MalformedURLException URL非法
     */
    public String retrieveFileNameFromUrl(String url) throws MalformedURLException {
        URL urlResource = new URL(url);
        String path = urlResource.getPath();
        return path.substring(path.lastIndexOf("/") + 1);
    }
}
